package flc.ast.fragment;

import static android.app.Activity.RESULT_OK;

import android.app.Dialog;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.os.Handler;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.blankj.utilcode.util.ConvertUtils;
import com.blankj.utilcode.util.TimeUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.chad.library.adapter.base.BaseQuickAdapter;
import com.google.gson.reflect.TypeToken;
import com.stark.picselect.config.PhotoConfig;
import com.stark.picselect.entity.SelectMediaEntity;
import com.stark.picselect.utils.MediaLoadManager;

import java.util.ArrayList;
import java.util.List;

import flc.ast.R;
import flc.ast.activity.AlbumDetailActivity;
import flc.ast.activity.FileSelectActivity;
import flc.ast.activity.LocalAlbumActivity;
import flc.ast.adapter.AddDataAdapter;
import flc.ast.adapter.AlbumAdapter;
import flc.ast.bean.MyAlbumBean;
import flc.ast.bean.MyAlbumItemBean;
import flc.ast.databinding.FragmentAlbumBinding;
import flc.ast.utils.AppSpUtils;
import flc.ast.utils.Content;
import io.reactivex.rxjava3.core.ObservableEmitter;
import stark.common.basic.base.BaseNoModelFragment;
import stark.common.basic.event.EventStatProxy;
import stark.common.basic.utils.MediaUtil;
import stark.common.basic.utils.RxUtil;
import stark.common.basic.utils.SPUtil;
import stark.common.basic.utils.StkPermissionHelper;
import stark.common.basic.utils.TimeUtil;
import stark.common.basic.view.StkTextView;
import stark.common.basic.view.container.StkRecycleView;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link AlbumFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class AlbumFragment extends BaseNoModelFragment<FragmentAlbumBinding> {

    private String imgPath;
    private Dialog myAddDialog;
    private EditText addName;
    private AddDataAdapter dataAdapter;
    private List<String> listSel = new ArrayList<>();
    private AlbumAdapter albumAdapter;


    @Override
    protected int onCreate() {
        return R.layout.fragment_album;
    }

    @Override
    protected void initView() {
        EventStatProxy.getInstance().statEvent1(getActivity(), mDataBinding.event1Container);
        EventStatProxy.getInstance().statEvent5(getActivity(), mDataBinding.event5Container);

        mDataBinding.ivAddAlbum.setOnClickListener(this);
        mDataBinding.ivLocalAlbumImg.setOnClickListener(this);

        mDataBinding.rvAlbumList.setLayoutManager(new LinearLayoutManager(mContext, LinearLayoutManager.HORIZONTAL, false));
        albumAdapter = new AlbumAdapter();
        mDataBinding.rvAlbumList.setAdapter(albumAdapter);
        albumAdapter.setOnItemClickListener(this);

        //新建相册弹框
        addDialog();
    }

    @Override
    protected void onClickCallback(View v) {
        switch (v.getId()) {
            case R.id.ivAddAlbum://添加相册
                listSel.clear();
                listSel.add("");
                dataAdapter.setList(listSel);
                myAddDialog.show();
                break;
            //创建弹框
            case R.id.ivDialogAddAlbumCancel://取消
                myAddDialog.dismiss();
                break;
            case R.id.tvDialogAddAlbumRight://确定
                String albumName = addName.getText().toString();
                if (TextUtils.isEmpty(albumName)) {
                    ToastUtils.showShort(R.string.please_input_album_name);
                } else if (listSel.size() <= 1) {
                    ToastUtils.showShort(R.string.please_import_file);
                } else {
                    myAddDialog.dismiss();
                    showDialog(getString(R.string.add_album_ing));
                    addAlbumData(albumName);
                }
                break;
            case R.id.ivLocalAlbumImg://本地相册
                startActivity(LocalAlbumActivity.class);
                break;
        }
    }

    @Override
    protected void onItemClickCallback(@NonNull BaseQuickAdapter<?, ?> adapter, @NonNull View view, int position) {
        if (adapter == dataAdapter) {
            if (TextUtils.isEmpty(dataAdapter.getItem(position))) {
                //添加相册数据
                Intent intent = new Intent(getActivity(), FileSelectActivity.class);
                startActivityForResult(intent, Content.SELECT_FILE_CODE);
            }
        } else if (adapter == albumAdapter) {
            AlbumDetailActivity.myBean = albumAdapter.getItem(position);
            startActivity(AlbumDetailActivity.class);
        }
    }

    @Override
    protected void initData() {
        getPermission();
    }

    @Override
    public void onResume() {
        super.onResume();
        getAlbumData();
    }

    //获取相册数据
    private void getAlbumData() {
        List<MyAlbumBean> listSp = AppSpUtils.getAlbumList();
        if (listSp != null && listSp.size() > 0) {
            albumAdapter.setList(listSp);
            mDataBinding.rvAlbumList.setVisibility(View.VISIBLE);
        } else {
            mDataBinding.rvAlbumList.setVisibility(View.GONE);
        }
    }

    //获取权限
    private void getPermission() {
        StkPermissionHelper.permission(StkPermissionHelper.Permission.ACCESS_IMAGE_VIDEO)
                .reqPermissionDesc(getString(R.string.get_local_album_permission))
                .callback(new StkPermissionHelper.ACallback() {
                    @Override
                    public void onGranted() {
                        getLocalData();
                    }
                }).request();
    }

    //获取本地视频数据
    private void getLocalData() {
        RxUtil.create(new RxUtil.Callback<List<SelectMediaEntity>>() {
            @Override
            public void doBackground(ObservableEmitter<List<SelectMediaEntity>> emitter) {
                List<SelectMediaEntity> list = new ArrayList<>();
                List<SelectMediaEntity> listSys = MediaLoadManager.loadAllMediaData(mContext, PhotoConfig.Mode.PHOTO);
                if (listSys != null || listSys.size() > 0) {
                    list.addAll(listSys);
                }
                emitter.onNext(list);
            }

            @Override
            public void accept(List<SelectMediaEntity> list) {
                if (list.size() == 0) return;
                //展示第一个视频
                imgPath = list.get(0).getPath();
                Glide.with(mContext).load(imgPath).into(mDataBinding.ivLocalAlbumImg);
                //获取本地视频数量大小
                long size = 0;
                for (SelectMediaEntity bean : list) {
                    size = size + bean.getSize();
                }
                mDataBinding.tvLocalAlbumSize.setText(getString(R.string.album_size, list.size(), ConvertUtils.byte2FitMemorySize(size, 2)));
            }
        });
    }

    //添加相册数据
    private void addAlbumData(String name) {
        //准备数据
        listSel.remove(0);
        List<MyAlbumItemBean> list = new ArrayList<>();
        for (String path : listSel) {
            list.add(new MyAlbumItemBean(path, false));
        }
        List<MyAlbumBean> listSave = new ArrayList<>();
        MyAlbumBean bean = new MyAlbumBean(TimeUtils.getNowString(), name, list);
        listSave.add(bean);
        //保存数据
        List<MyAlbumBean> listSp = AppSpUtils.getAlbumList();
        if (listSp != null && listSp.size() > 0) {
            listSp.addAll(listSave);
            AppSpUtils.saveAlbumList(listSp);
        } else {
            AppSpUtils.saveAlbumList(listSave);
        }
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                dismissDialog();
                getAlbumData();
            }
        }, 500);
    }

    //新建相册弹框
    private void addDialog() {
        myAddDialog = new Dialog(mContext, R.style.DialogStyle);
        View inflate = LayoutInflater.from(mContext).inflate(R.layout.dialog_add_album, null);
        myAddDialog.setContentView(inflate);
        //获取当前Activity所在的窗体
        Window dialogWindow = myAddDialog.getWindow();
        //设置Dialog从窗体中心弹出
        dialogWindow.setGravity(Gravity.BOTTOM);
        DisplayMetrics dm = getResources().getDisplayMetrics();
        //获得窗体的属性
        WindowManager.LayoutParams lp = dialogWindow.getAttributes();
        lp.width = (int) (dm.widthPixels * 1.0);
        lp.y = 0;
        // 将属性设置给窗体
        dialogWindow.setAttributes(lp);
        addName = inflate.findViewById(R.id.etDialogAddAlbumText);
        ImageView cancel = inflate.findViewById(R.id.ivDialogAddAlbumCancel);
        StkTextView right = inflate.findViewById(R.id.tvDialogAddAlbumRight);
        cancel.setOnClickListener(this);
        right.setOnClickListener(this);
        StkRecycleView recycleView = inflate.findViewById(R.id.rvDialogAddAlbumList);
        recycleView.setLayoutManager(new GridLayoutManager(mContext, 3));
        dataAdapter = new AddDataAdapter();
        recycleView.setAdapter(dataAdapter);
        dataAdapter.setOnItemClickListener(this);
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == Content.SELECT_FILE_CODE) {
            List<String> list = (List<String>) data.getSerializableExtra(Content.ListPath);
            if (list != null && list.size() > 0) {
                listSel.addAll(list);
                dataAdapter.setList(listSel);
            }
        }
    }

}